<template>
  <div class="chart-container">
    <div ref="chartRef" class="chart"></div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import * as echarts from 'echarts'

// 图表引用
const chartRef = ref(null)
// 图表实例
let chartInstance = null
// 定时器引用
let refreshTimer = null

// 从URL获取参数
function getUrlParams() {
  const params = {}
  const queryString = window.location.search.substring(1)
  const pairs = queryString.split('&')
  pairs.forEach(pair => {
    const [key, value] = pair.split('=')
    if (key && value) {
      params[decodeURIComponent(key)] = decodeURIComponent(value)
    }
  })
  return params
}

// 获取API数据并更新图表
async function updateChartWithData() {
  if (!chartInstance) return
  
  try {
    // 获取URL参数
    const params = getUrlParams()
    const lineId = params.lineId || '02'
    const stepName = params.stepName || 'DC'
    
    // 设置加载状态
    chartInstance.showLoading()
    
    // 调用API
    // 根据stepName决定调用哪个接口
    const apiUrl = stepName === 'HEL' 
        ? `http://192.168.8.100:5000/api/production/lot-pass-rank?lineId=${lineId}&stepName=${stepName}`
        : `http://192.168.8.100:5000/api/production?lineId=${lineId}&stepName=${stepName}`;
    
    const response = await fetch(apiUrl)
    const result = await response.json()
    
    if (result.success && result.data) {
      const data = result.data
      
      // 构建xAxis数据
      const xAxisData = [
        data.twoDaysAgoShift?.test || '两天前班次',
        data.yesterdayShift?.test || '昨天班次',
        '当班累计'
      ]
      
      // 添加时段数据
      if (data.currentShiftIntervals && Array.isArray(data.currentShiftIntervals)) {
        data.currentShiftIntervals.forEach(interval => {
          if (interval.date) {
            xAxisData.push(interval.date)
          }
        })
      }
      
      // 构建产能数据
      const channengData = [
        data.twoDaysAgoShift?.data || 0,
        data.yesterdayShift?.data || 0,
        data.currentShiftTotal || 0
      ]
      
      // 添加时段产能数据
      if (data.currentShiftIntervals && Array.isArray(data.currentShiftIntervals)) {
        data.currentShiftIntervals.forEach(interval => {
          channengData.push(interval.data || 0)
        })
      }
      
      // 检查是否全屏
      const isFullScreen = document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement;
      
      // 目标产能数据
      const targetData = [2250, 2250, 2250, 375, 375, 375, 375, 375, 375];
      
      // 确保数据长度匹配，不足时用默认值补齐
      const paddedChannengData = [...channengData];
      const paddedTargetData = [...targetData];
      const maxLength = Math.max(paddedChannengData.length, paddedTargetData.length);
      while (paddedChannengData.length < maxLength) {
        paddedChannengData.push(0);
      }
      while (paddedTargetData.length < maxLength) {
        paddedTargetData.push(0);
      }
      
      // 设置基础图表配置
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross'
          }
        },
        toolbox: {
          feature: {
            saveAsImage: { show: false }
          }
        },
        legend: {
          data: ['产能', '目标产能']
        },
        xAxis: {
          type: 'category',
          data: xAxisData,
          axisLabel: {
            rotate: 0,
            fontSize: 11, // 放大x轴字体
            // 全屏状态下设置白色字体
            color: isFullScreen ? '#ffffff' : undefined
          }
        },
        yAxis: {
          type: 'value',
          min: 0,
          // 全屏状态下设置白色字体
          axisLabel: isFullScreen ? { color: '#ffffff' } : {}
        },
        legend: {
          data: ['产能', '目标产能'],
          // 确保legend中的文字在全屏状态下为白色
          textStyle: {
            color: isFullScreen ? '#ffffff' : '#188df0'
          }
        },
        series: [{
          name: '产能',
          type: 'bar',
          data: paddedChannengData,
          itemStyle: {
            // 根据与目标产能的比较动态设置颜色
            color: function(params) {
              return params.value >= paddedTargetData[params.dataIndex] ? '#00cc66' : '#188df0';
            }
          },
          label: {
            show: true,
            // 使用ECharts内置的位置选项，确保标签在柱子内部居中
            position: 'inside',
            // 设置文本对齐方式
            align: 'center',
            // 设置垂直对齐方式
            verticalAlign: 'middle',
            formatter: '{c}',
            fontSize: 30,
            color: isFullScreen ? '#ffffff' : '#000'
          }
        }, {
          name: '目标产能',
          type: 'line',
          data: paddedTargetData,
          smooth: true,
          itemStyle: {
            color: '#ff6600'
          },
          lineStyle: {
            width: 3
          },
          symbol: 'circle',
          symbolSize: 8,
          label: {
            show: true,
            position: 'top',
            formatter: '{c}',
            fontSize: 18,
            color: isFullScreen ? '#ffffff' : '#ff6600'
          }
        }]
      }
      
      // 全屏状态下添加全局文本样式
      if (isFullScreen) {
        option.textStyle = {
          color: '#ffffff'
        };
      }
      
      chartInstance.setOption(option, true)
    }
  } catch (error) {
    console.error('获取数据失败:', error)
    
    // 检查是否全屏
    const isFullScreen = document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement;
    
    // 错误状态
    const option = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'cross'
        }
      },
      xAxis: {
        type: 'category',
        data: ['数据加载失败'],
        axisLabel: {
          fontSize: 16, // 放大x轴字体
          // 全屏状态下设置白色字体
          color: isFullScreen ? '#ffffff' : undefined
        }
      },
      yAxis: {
        type: 'value',
        // 全屏状态下设置白色字体
        axisLabel: isFullScreen ? { color: '#ffffff' } : {}
      },
      legend: {
        data: ['产能', '目标产能'],
        // 确保legend中的文字在全屏状态下为白色
        textStyle: {
          color: isFullScreen ? '#ffffff' : undefined
        }
      },
      series: [{
        name: '产能',
        type: 'bar',
        data: [0],
        itemStyle: {
          color: '#188df0'
        },
        label: {
          show: true,
          // 使用ECharts内置的位置选项，确保标签在柱子内部居中
          position: 'inside',
          // 设置文本对齐方式
          align: 'center',
          // 设置垂直对齐方式
          verticalAlign: 'middle',
          formatter: '{c}',
          fontSize: 16,
          color: isFullScreen ? '#ffffff' : '#000'
        }
      }, {
        name: '目标产能',
        type: 'line',
        data: [0],
        smooth: true,
        itemStyle: {
          color: '#ff6600'
        },
        lineStyle: {
          width: 3
        },
        symbol: 'circle',
        symbolSize: 8,
        label: {
          show: true,
          position: 'top',
          formatter: '{c}',
          fontSize: 12,
          color: isFullScreen ? '#ffffff' : '#ff6600'
        }
      }]
    };
    
    // 全屏状态下添加全局文本样式
    if (isFullScreen) {
      option.textStyle = {
        color: '#ffffff'
      };
    }
    chartInstance.setOption(option, true)
  } finally {
    chartInstance.hideLoading()
  }
}

// 初始化图表
function initChart() {
  if (chartRef.value) {
    // 销毁旧实例
    if (chartInstance) {
      chartInstance.dispose()
    }
    
    // 创建新实例
    chartInstance = echarts.init(chartRef.value)
    
    // 检查是否全屏
    const isFullScreen = document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement;
    
    // 设置初始配置
    const initialOption = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'cross'
        }
      },
      xAxis: {
        type: 'category',
        data: ['加载中...'],
        axisLabel: {
          fontSize: 16, // 放大x轴字体
          // 全屏状态下设置白色字体
          color: isFullScreen ? '#ffffff' : undefined
        }
      },
      yAxis: {
        type: 'value',
        // 全屏状态下设置白色字体
        axisLabel: isFullScreen ? { color: '#ffffff' } : {}
      },
      legend: {
        data: ['产能', '目标产能'],
        // 确保legend中的文字在全屏状态下为白色
        textStyle: {
          color: isFullScreen ? '#ffffff' : undefined
        }
      },
      series: [{
        name: '产能',
        type: 'bar',
        data: [0],
        itemStyle: {
          color: '#188df0'
        },
        label: {
          show: true,
          // 使用ECharts内置的位置选项，确保标签在柱子内部居中
          position: 'inside',
          // 设置文本对齐方式
          align: 'center',
          // 设置垂直对齐方式
          verticalAlign: 'middle',
          formatter: '{c}',
          fontSize: 16,
          color: isFullScreen ? '#ffffff' : '#000'
        }
      }, {
        name: '目标产能',
        type: 'line',
        data: [0],
        smooth: true,
        itemStyle: {
          color: '#ff6600'
        },
        lineStyle: {
          width: 3
        },
        symbol: 'circle',
        symbolSize: 8,
        label: {
          show: true,
          position: 'top',
          formatter: '{c}',
          fontSize: 12,
          color: isFullScreen ? '#ffffff' : '#ff6600'
        }
      }]
    };
    
    // 全屏状态下添加全局文本样式
    if (isFullScreen) {
      initialOption.textStyle = {
        color: '#ffffff'
      };
    }    chartInstance.setOption(initialOption, true)
    
    // 获取数据
    updateChartWithData()
    
    // 响应式调整
    window.addEventListener('resize', handleResize)
  }
}

// 处理窗口大小变化
function handleResize() {
  if (chartInstance) {
    chartInstance.resize()
  }
}

// 处理全屏状态变化
function handleFullscreenChange() {
  // 延迟重新设置图表选项，确保全屏状态已经完全改变
  setTimeout(() => {
    if (chartInstance) {
      updateChartWithData()
    }
  }, 100);
}

// 组件挂载时初始化图表
onMounted(() => {
  setTimeout(() => {
    initChart()
  }, 0)
  
  // 添加全屏变化事件监听器
  document.addEventListener('fullscreenchange', handleFullscreenChange)
  document.addEventListener('webkitfullscreenchange', handleFullscreenChange)
  document.addEventListener('mozfullscreenchange', handleFullscreenChange)
  document.addEventListener('MSFullscreenChange', handleFullscreenChange)
  
  // 设置定时刷新（5分钟 = 300000毫秒）
  refreshTimer = setInterval(() => {
    updateChartWithData()
  }, 300000)
})

// 组件卸载时清理资源
onUnmounted(() => {
  if (chartInstance) {
    chartInstance.dispose()
    chartInstance = null
  }
  window.removeEventListener('resize', handleResize)
  
  // 移除全屏变化事件监听器
  document.removeEventListener('fullscreenchange', handleFullscreenChange)
  document.removeEventListener('webkitfullscreenchange', handleFullscreenChange)
  document.removeEventListener('mozfullscreenchange', handleFullscreenChange)
  document.removeEventListener('MSFullscreenChange', handleFullscreenChange)
  
  // 清除定时器
  if (refreshTimer) {
    clearInterval(refreshTimer)
    refreshTimer = null
  }
})
</script>

<style scoped>
.chart-container {
  width: 100%;
  height: 100%;
  min-height: 500px;
  position: relative;
}

.chart {
  width: 100%;
  height: 100%;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .chart-container {
    min-height: 400px;
  }
}

@media (max-width: 480px) {
  .chart-container {
    min-height: 300px;
  }
}

/* 横屏模式适配 */
@media screen and (orientation: landscape) and (max-height: 500px) {
  .chart-container {
    min-height: calc(100vh - 40px);
  }
}

/* 全屏模式适配 */
:fullscreen .chart-container {
  min-height: unset;
  height: 100%;
  width: 100%;
  padding: 0;
  box-sizing: border-box;
  background-color: #000000;
}

:-webkit-full-screen .chart-container {
  min-height: unset;
  height: 100%;
  width: 100%;
  padding: 0;
  box-sizing: border-box;
  background-color: #000000;
}

:-moz-full-screen .chart-container {
  min-height: unset;
  height: 100%;
  width: 100%;
  padding: 0;
  box-sizing: border-box;
  background-color: #000000;
}

:-ms-fullscreen .chart-container {
  min-height: unset;
  height: 100%;
  width: 100%;
  padding: 0;
  box-sizing: border-box;
  background-color: #000000;
}
</style>